//
//  RoomStatesViewController.m
//  HallOrder
//
//  Created by 蒋 浩锋 on 12-10-19.
//  Copyright (c) 2012年 蒋 浩锋. All rights reserved.
//
#import "QuartzCore/QuartzCore.h"
#import "RoomStatesViewController.h"
#import "CommonObject/ServerNetworkCenter.h"
#import "CommonObject/ClientNetworkCenter.h"
#import "CommonObject/SocketDataHandle.h"
#import "Plugin/GMGridView/GMGridView.h"
#import "Plugin/GMGridView/GMGridViewLayoutStrategies.h"
#import "Plugin/MBProgressHUD/MBProgressHUD.h"
#import "RoomInfoViewController.h"
#import "Plugin/FPPopover/FPPopoverController.h"

@interface RoomStatesViewController () <SocketDataHandleDelegate, GMGridViewDataSource, GMGridViewActionDelegate, UIPopoverControllerDelegate, RoomInfoViewControllerDelegate>
{
    __gm_weak GMGridView                *_gmGridView;
    __weak IBOutlet UIScrollView        *roomStatesScrollView;
    __weak IBOutlet UISegmentedControl  *segment;
    NSMutableArray                      *roomArray;
    MBProgressHUD                       *HUD;
    NSTimer                             *timer;
    NSString                            *roomType;
    RoomStateCell                       *_selectedCell;
    UIPopoverController                 *popover;
    __weak IBOutlet FXLabel             *lblClerkName;
    RoomStatesObject                    *tmpRoomObj;
    RoomState   *tempState;
}

@end

@implementation RoomStatesViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self)
    {
        // Custom initialization
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    roomType = @"0";
    [SocketDataHandle sharedInstance].delegate = self;
    [segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    GMGridView *gmGridView = [[GMGridView alloc] initWithFrame:roomStatesScrollView.bounds];
    gmGridView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    gmGridView.backgroundColor = [UIColor clearColor];
    gmGridView.tag = 0;
    [roomStatesScrollView addSubview:gmGridView];
    _gmGridView = gmGridView;
    _gmGridView.layoutStrategy = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutHorizontalPagedLTR];
    _gmGridView.style = GMGridViewStyleSwap;
    _gmGridView.showFullSizeViewWithAlphaWhenTransforming = NO;
    _gmGridView.itemSpacing = 5;
    _gmGridView.minEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    _gmGridView.centerGrid = YES;
    _gmGridView.actionDelegate = self;
    _gmGridView.dataSource = self;
    _gmGridView.showsHorizontalScrollIndicator = NO;
    lblClerkName.text = [DataCenter sharedInstance].clerkName;
    [[ServerNetworkCenter sharedInstance] sentMsg:rtRoomStates:ShowType, [DataCenter sharedInstance].UDID, @"0", @"0", @"0", @"0",[SocketDataHandle sharedInstance].sysDate, @"",@"",nil];

    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.labelText = @"数据加载中...";
    [HUD show:YES];

    // Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [SocketDataHandle sharedInstance].delegate = self;
    [self reloadTimer];
}

- (void)viewDidUnload
{
    roomStatesScrollView = nil;
    segment = nil;
    //    _selectedCell = nil;
    lblClerkName = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [timer invalidate];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

// ////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark GMGridViewDataSource
// ////////////////////////////////////////////////////////////

- (NSInteger)numberOfItemsInGMGridView:(GMGridView *)gridView
{
    //    return [tempSongArray count];
    return tmpRoomObj.RoomStates.count;
}

- (CGSize)GMGridView:(GMGridView *)gridView sizeForItemsInInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    return CGSizeMake(160, 108);
}

- (GMGridViewCell *)GMGridView:(GMGridView *)gridView cellForItemAtIndex:(NSInteger)index
{
    if (tmpRoomObj.RoomStates.count > index)
    {
        RoomState *obj = [tmpRoomObj.RoomStates objectAtIndex:index];

        CGSize size = [self GMGridView:gridView sizeForItemsInInterfaceOrientation:[[UIApplication sharedApplication] statusBarOrientation]];

        RoomStateCell *cell = (RoomStateCell *)[gridView dequeueReusableCell];

        if (!cell)
        {
            cell = [[RoomStateCell alloc] initWithXib];
            cell.frame = CGRectMake(0, 0, size.width, size.height);
            cell.layer.masksToBounds = NO;
            cell.layer.cornerRadius  = 4;
            cell.layer.shadowColor   = [UIColor blackColor].CGColor;
            cell.layer.shadowOffset  = CGSizeMake(0, 0);
            cell.layer.shadowOpacity = 0.5;
            cell.backgroundColor     = [UIColor darkGrayColor];
        }

        cell.lblRoomNo.text = [NSString stringWithFormat:@"%@(%@)", obj.RoomNo, obj.LowLimitMoney];
        cell.lblKeRenXingMing.text = obj.GuestName;
        cell.lblDingFangRen.text = obj.ReserveClerk;
        cell.lblDaoDaShiJian.text = @"";
        cell.lblYuDingShiJian.text = @"";
        cell.backgroundColor = obj.color;

        /*
         *   0: 空房：RoomState=Null And RoomFlag <>1 And RoomFlag <>6 And Room_IFBad<>1
         *   1: 带位房：(RoomState =Null Or RoomState=R) And (RoomFlag=1)
         *   2: 预订房：RoomState =R And RoomFlag<>1
         *   3: 已开房：RoomState =I
         *   4: 结帐房：RoomState =S
         *   5: 清洁房：RoomState =L
         *   6: 并台房：RoomState =Null And RoomFlag=6
         *   7:维修房：RoomState =Null And Room_IfBad=1
         */
        switch (obj.room_State)
        {

            case 2:
                cell.backgroundColor = [self getColor:@"00CC00"];

                cell.lblDaoDaShiJian.text = [NSString stringWithFormat:@"抵:%@", obj.ArriveDateTime];
                cell.lblYuDingShiJian.text = [NSString stringWithFormat:@"订:%@", obj.ReserveDateTime];
                break;

            case 3:
                cell.backgroundColor = [self getColor:@"CC3333"];
                cell.lblDaoDaShiJian.text = [NSString stringWithFormat:@"开:%@", obj.CheckInDateTime];
                break;
            default:
                break;
        }

        return cell;
    }

    return nil;
}

- (BOOL)GMGridView:(GMGridView *)gridView canDeleteItemAtIndex:(NSInteger)index
{
    return NO; // index % 2 == 0;
}

// ////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark GMGridViewActionDelegate
// ////////////////////////////////////////////////////////////

- (void)GMGridView:(GMGridView *)gridView didTapOnItemAtIndex:(NSInteger)position
{
    if (tmpRoomObj.RoomStates.count > position)
    {
        _selectedCell = (RoomStateCell *)[gridView cellForItemAtIndex:position];
        tempState = [tmpRoomObj.RoomStates objectAtIndex:position];
        [DataCenter sharedInstance].roomNo = tempState.RoomNo;
        [DataCenter sharedInstance].tempMasterID = tempState.MasterID;
//        [[ServerNetworkCenter sharedInstance] sentMsg:rtRoomStateAndInfo:tempState.RoomNo,tempState.MasterID, @"0", nil];
        [self socketDataHandleDidRoomStateAndInfo:nil];
    }
}

- (UIColor *)getColor:(NSString *)hexColor
{
    unsigned int    red, green, blue;
    NSRange         range;

    range.length = 2;

    range.location = 0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
    range.location = 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
    range.location = 4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];

    return [UIColor colorWithRed:(float)(red / 255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}

-(void)socketDataHandleDidRoomStates:(RoomStatesObject *)obj
{
    tmpRoomObj = obj;
    [segment setTitle:[NSString stringWithFormat:@"空房(%d)",obj.NullCount] forSegmentAtIndex:1];
    [segment setTitle:[NSString stringWithFormat:@"带位房(%d)",obj.LeadCount] forSegmentAtIndex:2];
    [segment setTitle:[NSString stringWithFormat:@"预定房(%d)",obj.ReserverCount] forSegmentAtIndex:3];
    [segment setTitle:[NSString stringWithFormat:@"已开房(%d)",obj.InCount] forSegmentAtIndex:4];
    [segment setTitle:[NSString stringWithFormat:@"结账房(%d)",obj.SettleCount] forSegmentAtIndex:5];
    [segment setTitle:[NSString stringWithFormat:@"未走房(%d)",obj.RetainCount] forSegmentAtIndex:6];
    [segment setTitle:[NSString stringWithFormat:@"并台房(%d)",obj.MergerCount] forSegmentAtIndex:7];
    [segment setTitle:[NSString stringWithFormat:@"维修房(%d)",obj.BadCount] forSegmentAtIndex:8];
    [_gmGridView reloadData];
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)segmentAction:(UISegmentedControl *)Seg
{
    roomType = [NSString stringWithFormat:@"%d", Seg.selectedSegmentIndex];
    [self updateData:nil];
}

- (void)updateData:(NSTimer *)timer
{
    [[ServerNetworkCenter sharedInstance] sentMsg:rtRoomStates:ShowType, [DataCenter sharedInstance].UDID, roomType, @"0", @"0", @"0",[SocketDataHandle  sharedInstance].sysDate,@"",@"", nil];
    
}

- (void)reloadTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateData:) userInfo:nil repeats:YES];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"showPopoverVC"])
    {
        //        RoomStatesViewController *viewController = segue.destinationViewController;
        //        popover = [(UIStoryboardPopoverSegue *)segue popoverController];
        //        [popover setValue:[NSNumber numberWithInt:1] forKey:@"popoverBackgroundStyle"];
        //        [[[popover contentViewController]  view] setBackgroundColor:[UIColor clearColor]];
    }
}

- (void)socketDataHandleDidRoomStateAndInfo:(RoomStateAndInfo *)roomStateInfo
{
    RoomInfoViewController *viewController = [[RoomInfoViewController alloc] initWithStyle:UITableViewStyleGrouped];

    viewController.roomStateObj = tempState;
    viewController.roomInfoObj = roomStateInfo;
    popover = [[UIPopoverController alloc] initWithContentViewController:viewController];

    /*
     *   0: 空房：RoomState=Null And RoomFlag <>1 And RoomFlag <>6 And Room_IFBad<>1
     *   1: 带位房：(RoomState =Null Or RoomState=R) And (RoomFlag=1)
     *   2: 预订房：RoomState =R And RoomFlag<>1
     *   3: 已开房：RoomState =I
     *   4: 结帐房：RoomState =S
     *   5: 清洁房：RoomState =L
     *   6: 并台房：RoomState =Null And RoomFlag=6
     *   7:维修房：RoomState =Null And Room_IfBad=1
     */
    switch (tempState.room_State)
    {
        case 2:
            [popover setPopoverContentSize:CGSizeMake(250, 420)];
            break;

        case 3:
            [popover setPopoverContentSize:CGSizeMake(250, 470)];
            break;

        case 7:
            [popover setPopoverContentSize:CGSizeMake(250, 190)];
            break;

        default:
            [popover setPopoverContentSize:CGSizeMake(250, 220)];
            break;
    }
    //    [popover setPopoverContentSize:CGSizeMake(250, 500)];
    [popover setValue:[NSNumber numberWithInt:1] forKey:@"popoverBackgroundStyle"];
    [[[popover contentViewController]  view] setBackgroundColor:[UIColor clearColor]];
    popover.delegate = self;
    viewController.popover = popover;
    viewController.delegate = self;
    [popover presentPopoverFromRect:_selectedCell.bounds inView:_selectedCell permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    [SocketDataHandle sharedInstance].delegate = self;
}

- (void)disMiss
{
    [popover dismissPopoverAnimated:YES];
    [SocketDataHandle sharedInstance].delegate = self;
}

- (void)showOrderViewController
{
    [popover dismissPopoverAnimated:YES];
    UIStoryboard            *storyBoard = [UIStoryboard storyboardWithName:@"Storyboard_FoodOrder" bundle:nil];
    UINavigationController  *viewController = storyBoard.instantiateInitialViewController;
    [self presentModalViewController:viewController animated:YES];
}

@end